package http

import (
	"io/ioutil"
	"log"
	"net/http"
	"strings"
)

type cacheHandler struct {
	*Server
}

// ServeHTTP: parse the path /cache/
func (h *cacheHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	key := strings.Split(r.URL.EscapedPath(), "/")[2]
	if len(key) == 0 {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	m := r.Method
	switch m {
	case http.MethodPut:
		b, _ := ioutil.ReadAll(r.Body)
		if len(b) == 0 {
			w.WriteHeader(http.StatusBadRequest)
			return
		}
		err := h.Set(key, b)
		if err != nil {
			log.Println(err)
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		return
	case http.MethodGet:
		d, err := h.Get(key)
		if err != nil {
			log.Println(err)
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		if len(d) == 0 {
			w.WriteHeader(http.StatusNotFound)
			return
		}
		w.Write(d)
		return
	case http.MethodDelete:
		err := h.Del(key)
		if err != nil {
			log.Println(err)
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		return
	default:
		w.WriteHeader(http.StatusMethodNotAllowed)
		return
	}
}
